﻿using CQRSLearn.Features.Products.Commands.Create;
using CQRSLearn.Features.Products.Commands.Delete;
using CQRSLearn.Features.Products.Commands.Update;
using CQRSLearn.Features.Products.Notifications;
using CQRSLearn.Features.Products.Queries.Get;
using CQRSLearn.Features.Products.Queries.List;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace CQRSLearn.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        //private readonly ISender mediatr;
        private readonly IMediator mediatr;

        public ProductsController(IMediator mediatr)
        {
            this.mediatr = mediatr;
        }

        [HttpGet("{id:guid}")]
        public async Task<IActionResult> GetProductById(Guid id)
        {
            var product = await mediatr.Send(new GetProductQuery(id));
            if (product==null)
            {
                return NotFound();
            }
            return Ok(product);
        }

        [HttpGet("all")]
        public async Task<IActionResult> GetProductList() {
            var products = await mediatr.Send(new ListProductsQuery());
            if (products==null) { return NotFound(); }
            return Ok(products);
        }

        [HttpPost]
        public async Task<IActionResult> CreateProduct(CreateProductCommand command) {
            var productId = await mediatr.Send(command);
            if (productId==Guid.Empty)
            {
                return BadRequest();
            }
            await mediatr.Publish(new ProductCreatedNotification(productId));
            return Ok(new { id=productId});
        }

        [HttpPut]
        public async Task<IActionResult> UpdateProduct(UpdateProductCommand command) {
            var count= await mediatr.Send(command);
            return Ok(new {count=count });
        }
        [HttpDelete("{id:guid}")]
        public async void DeleteProduct(Guid id)
        {
            await mediatr.Send(new DeleteProductCommand(id));
        }
    }
}
